
這次的內容是,當我們滾輪滑動到圖片的位置,圖片會自動彈入,這在很多網站是很常見的功能!
作品實作
    const imges = document.querySelectorAll("img");
    window.addEventListener('scroll', debounce(scrollHandler));
imges選取網頁中的所有圖片元素
window.addEventListener('scroll', debounce(checkSlide)) 監聽'scroll' 狀態時執行函式scrollHandler
   function scrollHandler() {
        const windowBotton = window.scrollY + window.innerHeight; //視窗最底的那條線
        imges.forEach((img) => {
          let imgMiddle = img.offsetTop + img.height / 2;
          if (imgMiddle <= windowBotton) {
            img.classList.add("active");
          } else {
            img.classList.remove("active");
          }
        });
      }
windowBotton 為頁面已經滾動的垂直距離 + 當前視窗的可視高度,代表網頁滑動的總長
imgMiddle 為img頁面中的高度 + img本身的高度/2,代表每張圖片的中線在網頁中的高度
if (imgMiddle <= windowBotton) 如果windowBotton 滑動的距離超過imgMiddle Class增加active特效,反之則消除
  //當20毫秒內沒有動作則執行
  function debounce(func, wait = 20, immediate = true) {
        var timeout;
        return function () {
          var context = this,
            args = arguments;
          var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
      }
function debounce(func, wait = 20, immediate = true) :
這個函式的邏輯是說,當我們觸發一次函式時,會先用 clearTimeout(timeout) 清除前面的計時器並且重新設定 setTimeout(later, wait);
func 為我們要帶入的函式
wait 代表等待的時間
immediate 決定是否應立即執行 func,默認值為 true(立即執行)
later當我們等待了20毫秒後賦值timeout = null;
if (callNow)  如果滿足條件immediate為true,!timeout為false則執行func.apply(context, args)
JS30
[ Alex 宅幹嘛 ] 👨💻 深入淺出 Javascript30 快速導覽 | Day 13:Slide in on Scroll